const app = getApp();
import { baseUrl } from "../../../api/request";
import { getStorage, setStorage } from "../../../utils/localStorage";
import { getMapDistance } from "../../../utils/address";
import { navigationRoute_Info } from "../../../api/luxian";
import { routeLikes, generateRoute, startTraveling, village_Delete } from "../../../api/luxian.js";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //图片地址
    baseUrl: baseUrl,
    //navBar组件参数
    navData: {
      title: '规划完成',
      level: 11,
    },
    //自定义页面导航栏高度
    pageTop: app.globalData.navHeight + app.globalData.navTop + 10,
    latlng: {},
    //用户信息
    userInfo: {},
    //当前位置经度
    longitude: '',
    //当前位置维度
    latitude: '',
    //makers标记点数据
    markerData: [
      // {
      //     id: 1,
      //     label: {
      //         content: `当前位置`,
      //         color: '#4646A0',
      //         fontSize: 14,
      //         anchorX: 0,
      //         anchorY: 0,
      //     },
      //     longitude: '119.62',
      //     latitude: '29.12',
      // }
    ],
    //路线数组
    polylineData: [],
    lineTitleState: false,
    //路线数据
    // routeData: [
    //     {
    //         longitude: '119.62',
    //         latitude: '29.12'
    //     },
    //     {
    //         longitude: '119.59',
    //         latitude: '29.14'
    //     },
    //     {
    //         longitude: '119.62',
    //         latitude: '29.16'
    //     },
    // ],
    //路线规划类型
    infoData: {},
    //生成参数
    gateData: {},
    //选择路线索引
    xzRouteIndex: 0,
    //选择路线数据
    xzRouteData: {},
    //选择导航路线
    xzdhArr: [],
    //路线id
    travelId: undefined,
    //是否显示刷新按钮
    refreshStatus: false,
    //页面标识
    pageIdent: undefined,
    backDelta: 1,
    //保存路线按钮状态
    saveRouteState: false,
    //途径点数据
    waypointsArr: [],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({ userInfo: getStorage('user') });
    if (JSON.stringify(options) != "{}") {
      const item = JSON.parse(decodeURIComponent(options.data || "{}"));
      this.setData({ gateData: item, travelId: options.id, pageIdent: getStorage("pageId"), backDelta: options.backDelta });
      this.getInfo();
    } else {
      wx.showToast({
        icon: 'none',
        title: '详情参数获取失败',
        duration: 2000
      });
    };
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  //获取页面详情数据
  getInfo() {
    navigationRoute_Info({ travelId: this.data.travelId, userId: this.data.userInfo.id }).then(res => {
      res.data.data.image = res.data.data.image ? res.data.data.image.split(",") : [];

      const arr = res.data.data.routeVillageDtos.map((item, index) => ({
        ...item,
        lxName: index + 1
      }));
      arr.unshift({ lxName: '路线' });
      this.setData({
        xzdhArr: arr,
        infoData: res.data.data,
        longitude: res.data.data.startLongitude,
        latitude: res.data.data.startLatitude,
      });
      this.getRouteLine();
    });
  },

  //获取路线规划详细数据
  getRouteLine() {
    wx.showLoading({
      title: '地图加载中...',
      mask: true
    });
    let waypointsArr = [], makerArr = [];
    this.data.infoData.routeVillageDtos.forEach((item, index) => {
      waypointsArr.push(item.latitude + "," + item.longitude);
      makerArr.push({
        id: item.villageId,
        iconPath: "../../../image/icon/makerIcon1.png",
        width: 20,
        height: 20,
        label: {
          content: item.villageName,
          color: '#4646A0',
          fontSize: 14,
          anchorX: -25,
          anchorY: 0,
        },
        longitude: item.longitude,
        latitude: item.latitude,
      });
    });
    makerArr.unshift({
      id: 1,
      iconPath: "../../../image/icon/dangqianweizhi.png",
      width: 30,
      height: 30,
      label: {
        content: "起始位置",
        color: '#4646A0',
        fontSize: 14,
        anchorX: -20,
        anchorY: -45,
      },
      longitude: this.data.infoData.startLongitude,
      latitude: this.data.infoData.startLatitude,
    });
    makerArr.push({
      id: 9999,
      iconPath: "../../../image/icon/makerIcon1.png",
      width: 20,
      height: 20,
      label: {
        content: "目的地",
        color: '#4646A0',
        fontSize: 14,
        anchorX: -20,
        anchorY: 20,
      },
      longitude: this.data.infoData.endLongitude,
      latitude: this.data.infoData.endLatitude,
    });
    this.setData({
      waypointsArr: waypointsArr,
      markerData: makerArr,
      xzRouteData: {
        name: makerArr[0].label.content,
        longitude: makerArr[0].longitude,
        latitude: makerArr[0].latitude,
      },
    });
    this.startRoute();
  },

  //开始规划路线
  startRoute() {
    app.globalData.wxMapSdk.direction({
      mode: this.data.infoData.travelMode === '自驾游' ? 'driving' : this.data.infoData.travelMode === '步行' ? 'walking' : 'bicycling', //可选值：'driving'（驾车）、'walking'（步行）、'bicycling'（骑行），不填默认：'driving',可不填
      from: {
        longitude: this.data.infoData.startLongitude,
        latitude: this.data.infoData.startLatitude
      },
      to: {
        longitude: this.data.infoData.endLongitude,
        latitude: this.data.infoData.endLatitude,
      },
      waypoints: this.data.waypointsArr.join(";"),
      sig: "h3mJXYYwtOs1lHXho4ohnD4iaZpXlS",
      success: (res) => {
        if (res.status === 0) {
          let { polyline } = res.result.routes[0], pl = [], kr = 1000000;
          //坐标解压
          for (let i = 2; i < polyline.length; i++) {
            polyline[i] = Number(polyline[i - 2]) + Number(polyline[i]) / kr;
          };
          //将解压后的坐标放入点串数组pl中
          for (let i = 0; i < polyline.length; i += 2) {
            pl.push({ longitude: polyline[i + 1], latitude: polyline[i] })
          };
          //设置polyline属性，将路线显示出来,将解压坐标第一个数据作为起点
          let polyLineItem = [{
            points: pl,      // [  {      longitude: '119.62',     latitude: '29.12' } ],
            color: '#4E4AAB',
            width: 8,
            arrowLine: true,
            arrowIconPath: '',
            borderColor: '',
            borderWidth: 0,
          }];
          this.setData({
            polylineData: polyLineItem
          });
        };
        wx.hideLoading();
      },
      fail: (err) => {
        console.log(err, '腾讯地图api报错了');
        wx.hideLoading();
      }
    });
  },

  //导航路线选择
  xzRouteTap(e) {
    const item = e.currentTarget.dataset.item,
      index = e.currentTarget.dataset.index;
    if (index === 0) {
      this.getInfo();
    } else {
      app.globalData.wxMapSdk.direction({
        mode: this.data.infoData.travelMode === '自驾游' ? 'driving' : this.data.travelMode === '步行' ? 'walking' : 'bicycling', //可选值：'driving'（驾车）、'walking'（步行）、'bicycling'（骑行），不填默认：'driving',可不填
        from: {
          longitude: this.data.infoData.startLongitude,
          latitude: this.data.infoData.startLatitude
        },
        to: {
          longitude: item.longitude,
          latitude: item.latitude,
        },
        sig: "h3mJXYYwtOs1lHXho4ohnD4iaZpXlS",
        success: (res) => {
          if (res.status === 0) {
            let { polyline } = res.result.routes[0], pl = [], kr = 1000000;
            //坐标解压
            for (let i = 2; i < polyline.length; i++) {
              polyline[i] = Number(polyline[i - 2]) + Number(polyline[i]) / kr;
            };
            //将解压后的坐标放入点串数组pl中
            for (let i = 0; i < polyline.length; i += 2) {
              pl.push({ longitude: polyline[i + 1], latitude: polyline[i] })
            };
            //设置polyline属性，将路线显示出来,将解压坐标第一个数据作为起点
            let polyLineItem = [{
              points: pl,      // [  {      longitude: '119.62',     latitude: '29.12' } ],
              color: '#4E4AAB',
              width: 6,
              arrowLine: true,
              arrowIconPath: '',
              borderColor: '',
              borderWidth: 0,
            }];
            this.setData({
              xzRouteData: {
                name: this.data.markerData[index].label.content,
                longitude: this.data.markerData[index].longitude,
                latitude: this.data.markerData[index].latitude,
              },
              longitude: item.longitude,
              latitude: item.latitude,
              polylineData: polyLineItem,
              refreshStatus: true,
            });
          };
        },
        fail: (err) => {
          console.log(err, '腾讯地图api报错了');
        }
      });
    };
    this.setData({ xzRouteIndex: index });

  },

  //线路规划列表title点击事件
  lineTitleTap(e) {
    const state = e.currentTarget.dataset.state;
    this.setData({
      lineTitleState: !state
    });
  },
  //线路推荐列表点赞按钮点击事件
  commentClick(e) {
    let that = this.data,
      item = e.currentTarget.dataset.item,
      flag = !item.likeState ? true : false;
    routeLikes({ userId: that.userInfo.id, travelId: item.travelId, state: flag }).then(res => {
      let state = "infoData.likeState", num = "infoData.likeNumber";
      if (res.data.code === 200) {
        wx.showToast({
          icon: 'none',
          title: res.data.msg,
          duration: 1000,
        })
        this.setData({
          [state]: flag,
          [num]: !item.likeState ? item.likeNumber + 1 : item.likeNumber - 1
        });
      };
    });
  },
  //刷新按钮点击事件
  shxingTap() {
    setStorage("pageId", "refresh");
    wx.redirectTo({
      url: '/pagesLuxian/pages/loading/index?form=' + encodeURI(JSON.stringify(this.data.gateData)),
    });
  },
  //开始导航按钮点击事件
  daoHangTap() {
    console.log(this.data.xzRouteData, 'xzRouteData');
    wx.showModal({
      title: "提示",
      content: "是否按照你选择的路段开始导航",
      cancelText: "取消",
      cancelColor: "#eb0c0c",
      confirmText: "确定",
      confirmColor: "#4646A0",
      success: (res => {
        if (res.confirm) {
          const data = {
            travelId: this.data.infoData.travelId,
            userId: this.data.userInfo.id,
          };
          startTraveling(data).then(res => {
            if (res.data.code === 200) {
              wx.showToast({
                icon: 'none',
                title: res.data.msg,
                duration: 2000
              });
              setTimeout(() => {
                wx.openLocation({
                  name: this.data.xzRouteData.name,
                  latitude: +this.data.xzRouteData.latitude,
                  longitude: +this.data.xzRouteData.longitude
                });
              }, 2000)
            } else {
              wx.showToast({
                icon: 'none',
                title: res.data.msg,
                duration: 2000
              });
            };

          });
        };
      }),
    });

  },
  //内容点击事件
  listTap(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pagesLuxian/pages/detail/index?id=' + id,
    })
  },
  //村落删除按钮点击事件
  sunloDelete(e) {
    const item = e.currentTarget.dataset.item;
    wx.showModal({
      title: '警告',
      content: `请确定是否要删除${item.villageName}`,
      complete: (res) => {
        if (res.confirm) {
          village_Delete({ travelId: this.data.infoData.travelId, villageId: item.villageId }).then(res => {
            wx.showToast({
              icon: 'none',
              title: res.data.msg,
              duration: 2000,
            });
            res.data.code === 200 ? setTimeout(() => { this.getInfo(); }, 2000) : false;
          });
        };
      }
    });
  },

  //乡村列表点击事件
  xcListTap(e) {
    const item = e.currentTarget.dataset.item;
    wx.navigateTo({
      url: '/pagesShouYe/pages/xaingcunDetail/index?id=' + item.villageId,
    });
  },

  //保存路线按钮点击事件
  saveRouteTap() {
    this.setData({ saveRouteState: true });
    const { infoData, userInfo } = this.data;
    startTraveling({ userId: userInfo.id, travelId: infoData.travelId }).then(res => {
      wx.showToast({
        icon: 'none',
        title: res.data.code === 200 ? '保存路线成功' : res.data.msg,
        duration: 2000
      });
      setTimeout(() => {
        this.setData({ saveRouteState: false });
      }, 1000);
    });
  },

  /* 图片放大功能 */
  imgTap(e) {
    const url = e.currentTarget.dataset.url,
      urlList = e.currentTarget.dataset.urllist;
    if (url) {
      const arr = urlList.map(item => this.data.baseUrl + item);
      app.imagePreview(url, arr);
    };
  },

  /* 返回页面点击事件 */
  back() {
    wx.navigateBack();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})